package resources;

import java.io.IOException;
import java.util.List;

import javax.faces.FacesException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.primefaces.context.RequestContext;

import users.Instructor;
import users.Student;
import users.UnknownUser;
import users.User;

@ManagedBean
@SessionScoped
public class UserSession {
	private User user = new UnknownUser();
	private boolean isLoggedIn=false;
	public void setUser(User usr){this.user=usr;}
	public void setIsLoggedIn(boolean isLoggedIn)
	{this.isLoggedIn=isLoggedIn;}
	public User getUser(){return user;}
	public boolean getIsLoggedIn(){return isLoggedIn;}
	
	public boolean loginUser()
	{
		
		if(isLoggedIn){
			FacesContext ctx = FacesContext.getCurrentInstance();
	
	        ExternalContext extContext = ctx.getExternalContext();
	        String url = extContext.encodeActionURL(
	        		ctx.getApplication().getViewHandler().getActionURL(ctx, "/Welcome.xhtml"));
	        try {
	
	            extContext.redirect(url);
	        } catch (IOException ioe) {
	            throw new FacesException(ioe);
	
	        }
	        return true;
		}
		return false;
	}
	public void loginUnknownUser()
	{
		RequestContext context = RequestContext.getCurrentInstance();
		if(user.getUsername()!=null) System.out.println(user.getUsername());
		setIsLoggedIn(false);
		checkUser();
	}
	private void setNewUser(User user)
	{
		this.user=user;
		System.out.println(user.getTypeOfUser());
		
	}
	private boolean checkUser()
	{
		if(user==null) return false;
		if(user.getUsername()==null&&user.getPassword()==null) return false;
		if(user.getUsername().equals("")||user.getPassword().equals("")) return false;
		SessionDB session = new SessionDB();
		System.out.println("User: "+user.getUsername()+"   "+ user.getPassword());
		List<User> list = session.getUsers();
		for(User u: list)
			if((user.getUsername().equals(u.getUsername()))&&(user.getPassword().equals(u.getPassword()))){
				setNewUser(u);
				System.out.println("don't set tryue");
				setIsLoggedIn(true);
				return true;}
		setIsLoggedIn(false);
		return false;
	}
}
